package com.yanfan.iot.ruleEngine;

import com.alibaba.fastjson2.JSON;
import com.dtflys.forest.http.ForestRequest;
import com.yanfan.http.service.HttpClientFactory;
import com.yanfan.iot.domain.Bridge;
import com.yanfan.iot.domain.HttpClient;
import com.yanfan.iot.service.IBridgeService;
import com.yanfan.iot.service.IHttpClientService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import org.springframework.beans.factory.annotation.Autowired;

@LiteflowComponent("httpBridge")
public class HttpBridge extends NodeComponent {

    @Autowired
    private IHttpClientService httpClientService;
    @Autowired
    private IBridgeService bridgeService;

    @Override
    public void process() throws Exception {
        // 获取上下文对象
        MsgContext cxt = this.getContextBean(MsgContext.class);
        Integer id = cxt.getData("httpBridgeID");
        Bridge bridge = bridgeService.selectBridgeById(Long.valueOf(id));
        if (bridge != null) {
            HttpClient config = JSON.parseObject(bridge.getConfigJson(), HttpClient.class);
            ForestRequest request = HttpClientFactory.instance(httpClientService.buildhttpclientconfig(config));
            if (config.getRequestBody() != "") {
                request.addBody(cxt.placeholders(config.getRequestBody()));
            } else {
                request.addBody(cxt.getPayload());
            }
            request.execute();
        }
    }
}
